# -*- Python -*-

import os
import platform
import re
import subprocess
import tempfile

import lit.formats
import lit.util

from lit.llvm import llvm_config

# Configuration file for the 'lit' test runner.

from urllib.request import urlopen

IsWindows = platform.system() == 'Windows'

if IsWindows and not execute_external:
  # Use real Windows path separators so if a test fails, one can copy/paste cmds
  def fixupPath(path):
    return os.path.normpath(path)
else:
  def fixupPath(path):
    return path

# name: The name of this test suite.
config.name = 'Cling'

# testFormat: The test format to use to interpret tests.
#
# For now we require '&&' between commands, until they get globally killed and
# the test runner updated.
config.test_format = lit.formats.ShTest(not llvm_config.use_lit_shell)

# suffixes: A list of file extensions to treat as test files.
config.suffixes = ['.C']

# excludes: A list of directories to exclude from the testsuite. The 'Inputs'
# subdirectories contain auxiliary inputs for various tests in their parent
# directories.
config.excludes = ['Inputs', 'CMakeLists.txt', 'README.txt', 'LICENSE.txt', 'debuginfo-tests']

# test_source_root: The root path where tests are located.
config.test_source_root = os.path.dirname(__file__)

# test_exec_root: The root path where tests should be run.
config.test_exec_root = os.path.join(config.cling_obj_root, 'test')

llvm_config.use_default_substitutions()

llvm_config.use_clang()

config.substitutions.append(
    ('%src_include_dir', config.cling_src_root + '/include'))


# Propagate path to symbolizer for ASan/MSan.
llvm_config.with_system_environment(
    ['ASAN_SYMBOLIZER_PATH', 'MSAN_SYMBOLIZER_PATH'])

config.substitutions.append(('%PATH%', config.environment['PATH']))

# We want to invoke the system clang. Or not?
config.substitutions = [x for x in config.substitutions if x[0] != ' clang ']

config.substitutions.append(('%cling_obj_root', config.cling_obj_root))
incDir = os.path.join(config.llvm_obj_root, 'tools', 'clang', 'include')
config.substitutions.append( ('%cling', config.llvm_tools_dir + '/cling --nologo -I%s' % fixupPath(incDir)) )

config.substitutions.append(('%std_cxx', 'c++' + config.cxx_standard))

if platform.system() in ['Windows']:
  config.substitutions.append(('%dllexport', '"__declspec(dllexport)"'))
  config.substitutions.append(('%fPIC', ''))
else:
  config.substitutions.append(('%dllexport', ''))
  config.substitutions.append(('%fPIC', '-fPIC'))

if IsWindows and execute_external:
  config.substitutions.append(('%mkdir', 'mkdir'))
  config.substitutions.append(('%rmdir', 'rmdir /s /q'))
  config.substitutions.append(('%rm', 'del /s /q'))
else:
  config.substitutions.append(('%mkdir', 'mkdir -p'))
  config.substitutions.append(('%rmdir', 'rm -rf'))
  config.substitutions.append(('%rm', 'rm -f'))

# Don't add tests to history
os.environ['CLING_NOHISTORY'] = '1'

# FIXME: Find nicer way to prohibit this.
config.substitutions.append(
    (' cling ', """*** Do not use 'cling' in tests, use '%cling'. ***""") )

config.substitutions.append(('%shlibext', config.shlibext))

### Features

# Shell execution
if platform.system() not in ['Windows'] or lit_config.getBashPath() != '':
    config.available_features.add('shell')

lit.util.usePlatformSdkOnDarwin(config, lit_config)

# ROOT adds features that "heal" some of cling's tests; need to detect
# vanilla vs cling-as-part-of-ROOT. The latter has no `lib/UserInterface/textinput/`:
if os.path.isdir(os.path.join(config.cling_src_root, 'lib', 'UserInterface', 'textinput')):
  config.available_features.add('vanilla-cling')

libcudart_path = lit.util.which('libcudart.so', config.environment.get('LD_LIBRARY_PATH',''))
if libcudart_path is not None:
  config.available_features.add('cuda-runtime')
  # set the CUDA SDK root path
  # necessary if CUDA is not installed under /usr/local/
  config.substitutions.append(('%cudapath', libcudart_path[0:-len('/lib64/libcudart.so')]))
  # limit the number of usable GPUs in a system
  # https://developer.nvidia.com/blog/cuda-pro-tip-control-gpu-visibility-cuda_visible_devices/
  if 'CUDA_VISIBLE_DEVICES' in os.environ:
    config.environment['CUDA_VISIBLE_DEVICES'] = os.environ['CUDA_VISIBLE_DEVICES']
  # set the CUDA sm level for the tests (e.g. "export CLING_TEST_CUDA_SM_LEVEL=35")
  # if no sm level is set, the default of cling will be used
  if 'CLING_TEST_CUDA_SM_LEVEL' in os.environ:
      config.substitutions.append(('%cudasmlevel', '--cuda-gpu-arch=sm_' + os.environ['CLING_TEST_CUDA_SM_LEVEL']))
  else:
      config.substitutions.append(('%cudasmlevel', ""))
